package com.hmdp.controller;


import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.ShopType;
import com.hmdp.service.IShopTypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

import static com.hmdp.utils.RedisConstants.CACHE_SHOPTYPE;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@RestController
@RequestMapping("/shop-type")
public class ShopTypeController {

    @Autowired
    StringRedisTemplate redisTemplate;
    @Resource
    private IShopTypeService typeService;

    @GetMapping("list")
    public Result queryTypeList() {
        //查询缓存
        List<String> list = redisTemplate.opsForList().range(CACHE_SHOPTYPE + "list", -0,-1 );
        //如果有值
        if(list.size()!=0){
            List<ShopType> typeList = new ArrayList<>();
            for(String type : list){
                typeList.add(JSONUtil.toBean(type, ShopType.class));
            }
            return Result.ok(typeList);
        }
        //如没有就查询数据库
        List<ShopType> typeList = typeService
                .query().orderByAsc("sort").list();
        if(typeList.size()==0){
            Result.ok("查询错误");
        }
        List<String> typeListStrings = new ArrayList<>();
        for(ShopType shopType : typeList){
            String s = JSONUtil.toJsonStr(shopType);
            typeListStrings.add(s);
        }
        //再添加到缓存中
        redisTemplate.opsForList().leftPushAll(CACHE_SHOPTYPE+"list",typeListStrings);
        return Result.ok(typeList);
    }
}
